<?php


namespace Yond\LaravelDomain\Models\Casts;


use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use LogicException;
use Yond\LaravelDomain\Models\Concerns\HasBelongsToManyField;

class BelongsToManyField implements CastsAttributes
{
    protected string $relation;
    protected string $field;

    public function __construct($relation, $field = 'id')
    {
        $this->relation = $relation;
        $this->field = $field;
    }

    protected function check($model)
    {
        if (!in_array(HasBelongsToManyField::class, class_uses_recursive($model))) {
            throw new LogicException('Model must use HasBelongsToManyField Trait when use BelongsToManyField Cast');
        }

        $relationship = $model->{$this->relation}();
        if (!($relationship instanceof BelongsToMany)) {
            throw new LogicException('relation '. $this->relation .' must be BelongsToMany when use BelongsToManyField Cast');
        }

    }

    public function get($model, string $key, $value, array $attributes)
    {
        $this->check($model);

        return $model->loadMissing($this->relation.':'.$this->field)->{$this->relation}->pluck($this->field);
    }

    public function set($model, string $key, $value, array $attributes): array
    {
        $this->check($model);

        /** @var HasBelongsToManyField $model */
        if (!$model->exists) {
            $model->queuedAttachFields[$this->relation] = $value;
        } else {
            $model->{$this->relation}()->sync($value);
        }

        return [];
    }
}
